package controllers

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/beego/beego/v2/core/logs"

	"supershare/backend/middleware"
	"supershare/backend/models"
	"supershare/backend/services"
)

// DouyinController 抖音配置控制器
type DouyinController struct {
	BaseController
}

// @router /api/v1/douyin [get]
func (c *DouyinController) List() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Fail("未授权访问")
		return
	}

	// 获取分页参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("pageSize", 10)

	// 获取过滤条件
	filters := make(map[string]interface{})
	if storeId, err := c.GetInt64("store_id"); err == nil && storeId > 0 {
		filters["store_id"] = storeId
	}
	if status, err := c.GetInt("status"); err == nil {
		filters["status"] = status
	}

	// 加盟商只能查看自己的数据
	if admin.FranchiseId > 0 {
		filters["franchise_id"] = admin.FranchiseId
	}

	// 查询数据
	list, total, err := models.GetDouyinList(page, pageSize, filters)
	if err != nil {
		c.Fail("获取抖音配置列表失败")
		return
	}

	c.SuccessWithPagination("获取成功", list, total, page, pageSize)
}

// @router /api/v1/douyin [post]
func (c *DouyinController) Create() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Fail("未授权访问")
		return
	}

	var douyin models.Douyin
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &douyin); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "参数解析失败",
		}
		c.ServeJSON()
		return
	}

	// 设置创建者信息
	douyin.BaseModel.CreatedAt = time.Now().Unix()
	douyin.BaseModel.UpdatedAt = douyin.CreatedAt
	douyin.BaseModel.CreatedBy = admin.Username
	douyin.BaseModel.UpdatedBy = admin.Username

	// 设置加盟商ID
	douyin.BaseModel.FranchiseId = admin.FranchiseId

	// 添加数据
	id, err := models.AddDouyin(&douyin)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "添加抖音配置失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
		"data": map[string]interface{}{
			"id": id,
		},
	}
	c.ServeJSON()
}

// @router /api/v1/douyin/:id [get]
func (c *DouyinController) Detail() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Fail("未授权访问")
		return
	}

	id, err := c.GetInt64(":id")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "参数错误",
		}
		c.ServeJSON()
		return
	}

	// 查询数据
	douyin, err := models.GetDouyinById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "获取抖音配置详情失败",
		}
		c.ServeJSON()
		return
	}
	if douyin == nil {
		c.Data["json"] = map[string]interface{}{
			"code": 404,
			"msg":  "抖音配置不存在",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if admin.FranchiseId > 0 && douyin.BaseModel.FranchiseId != admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"code": 403,
			"msg":  "没有权限访问此数据",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
		"data": douyin,
	}
	c.ServeJSON()
}

// @router /api/v1/douyin/:id [put]
func (c *DouyinController) Update() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Fail("未授权访问")
		return
	}

	id, err := c.GetInt64(":id")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "参数错误",
		}
		c.ServeJSON()
		return
	}

	// 查询数据
	douyin, err := models.GetDouyinById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "获取抖音配置详情失败",
		}
		c.ServeJSON()
		return
	}
	if douyin == nil {
		c.Data["json"] = map[string]interface{}{
			"code": 404,
			"msg":  "抖音配置不存在",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if admin.FranchiseId > 0 && douyin.BaseModel.FranchiseId != admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"code": 403,
			"msg":  "没有权限修改此数据",
		}
		c.ServeJSON()
		return
	}

	// 解析JSON数据
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, douyin); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "参数解析失败",
		}
		c.ServeJSON()
		return
	}

	// 设置更新者信息
	douyin.BaseModel.UpdatedAt = time.Now().Unix()
	douyin.BaseModel.UpdatedBy = admin.Username

	// 确保不改变所属加盟商
	douyin.BaseModel.FranchiseId = admin.FranchiseId

	// 更新数据
	err = models.UpdateDouyin(douyin)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "更新抖音配置失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
	}
	c.ServeJSON()
}

// @router /api/v1/douyin/:id [delete]
func (c *DouyinController) Delete() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Fail("未授权访问")
		return
	}

	id, err := c.GetInt64(":id")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "参数错误",
		}
		c.ServeJSON()
		return
	}

	// 查询数据，确保存在且属于当前加盟商
	douyin, err := models.GetDouyinById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "获取抖音配置详情失败",
		}
		c.ServeJSON()
		return
	}
	if douyin == nil {
		c.Data["json"] = map[string]interface{}{
			"code": 404,
			"msg":  "抖音配置不存在",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if admin.FranchiseId > 0 && douyin.BaseModel.FranchiseId != admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"code": 403,
			"msg":  "没有权限删除此数据",
		}
		c.ServeJSON()
		return
	}

	// 删除数据
	err = models.DeleteDouyin(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "删除抖音配置失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
	}
	c.ServeJSON()
}

// @router /api/v1/douyin/:id/sync [post]
func (c *DouyinController) Sync() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Fail("未授权访问")
		return
	}

	id, err := c.GetInt64(":id")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "参数错误",
		}
		c.ServeJSON()
		return
	}

	// 获取抖音配置
	douyin, err := models.GetDouyinById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "获取抖音配置失败",
		}
		c.ServeJSON()
		return
	}
	if douyin == nil {
		c.Data["json"] = map[string]interface{}{
			"code": 404,
			"msg":  "抖音配置不存在",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if admin.FranchiseId > 0 && douyin.BaseModel.FranchiseId != admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"code": 403,
			"msg":  "没有权限操作此数据",
		}
		c.ServeJSON()
		return
	}

	// 创建抖音API服务
	apiService := services.NewDouyinAPIService()

	// 同步团购活动
	groups, err := apiService.SyncGroups(douyin.PoiId)
	if err != nil {
		logs.Error("同步抖音团购活动失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "同步抖音团购活动失败",
		}
		c.ServeJSON()
		return
	}

	// 更新团购活动
	for _, group := range groups {
		// 转换数据
		douyinGroup := &models.DouyinGroup{
			DouyinId:      douyin.Id,
			StoreId:       douyin.StoreId,
			StoreName:     douyin.StoreName,
			Title:         group["title"].(string),
			Description:   group["description"].(string),
			OriginalPrice: int(group["original_price"].(float64)),
			GroupPrice:    int(group["group_price"].(float64)),
			MinCount:      int(group["min_count"].(float64)),
			MaxCount:      int(group["max_count"].(float64)),
			StartTime:     int64(group["start_time"].(float64)),
			EndTime:       int64(group["end_time"].(float64)),
			Status:        int(group["status"].(float64)),
			DouyinGroupId: group["group_id"].(string),
			SoldCount:     int(group["sold_count"].(float64)),
			ActivityRules: group["activity_rules"].(string),
			ServiceTerms:  group["service_terms"].(string),
			Images:        group["images"].(string),
			LastSyncTime:  time.Now().Unix(),
		}

		// 设置加盟商ID和创建者信息
		douyinGroup.BaseModel.FranchiseId = douyin.FranchiseId
		douyinGroup.BaseModel.CreatedBy = admin.Username
		douyinGroup.BaseModel.UpdatedBy = admin.Username

		// 检查团购活动是否存在
		existingGroup, err := models.GetDouyinGroupByDouyinGroupId(douyinGroup.DouyinGroupId)
		if err != nil {
			logs.Error("查询抖音团购活动失败: %v", err)
			continue
		}

		if existingGroup == nil {
			// 添加新团购活动
			douyinGroup.BaseModel.CreatedAt = time.Now().Unix()
			douyinGroup.BaseModel.UpdatedAt = douyinGroup.CreatedAt
			_, err = models.AddDouyinGroup(douyinGroup)
			if err != nil {
				logs.Error("添加抖音团购活动失败: %v", err)
			}
		} else {
			// 更新现有团购活动
			douyinGroup.BaseModel.Id = existingGroup.Id
			douyinGroup.BaseModel.UpdatedAt = time.Now().Unix()
			err = models.UpdateDouyinGroup(douyinGroup)
			if err != nil {
				logs.Error("更新抖音团购活动失败: %v", err)
			}
		}
	}

	// 同步订单
	// 获取最近24小时的订单
	startTime := time.Now().Add(-24 * time.Hour).Unix()
	endTime := time.Now().Unix()
	orders, err := apiService.SyncOrders(douyin.PoiId, startTime, endTime)
	if err != nil {
		logs.Error("同步抖音订单失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "同步抖音订单失败",
		}
		c.ServeJSON()
		return
	}

	// 更新订单
	for _, order := range orders {
		// 转换数据
		douyinOrder := &models.DouyinGroupOrder{
			DouyinId:         douyin.Id,
			StoreId:          douyin.StoreId,
			StoreName:        douyin.StoreName,
			OrderId:          order["order_id"].(string),
			OrderTime:        int64(order["order_time"].(float64)),
			GroupTitle:       order["group_title"].(string),
			UserName:         order["user_name"].(string),
			UserPhone:        order["user_phone"].(string),
			Quantity:         int(order["quantity"].(float64)),
			TotalPrice:       int(order["total_price"].(float64)),
			Status:           order["status"].(string),
			ProcessStatus:    order["process_status"].(string),
			IsProcessed:      int(order["is_processed"].(float64)),
			ProcessTime:      int64(order["process_time"].(float64)),
			RefundStatus:     order["refund_status"].(string),
			Remark:           order["remark"].(string),
			DouyinRemark:     order["douyin_remark"].(string),
			VoucherCode:      order["voucher_code"].(string),
			VoucherValidTime: int64(order["voucher_valid_time"].(float64)),
			IsUsed:           int(order["is_used"].(float64)),
			UseTime:          int64(order["use_time"].(float64)),
		}

		// 设置加盟商ID和创建者信息
		douyinOrder.BaseModel.FranchiseId = douyin.FranchiseId
		douyinOrder.BaseModel.CreatedBy = admin.Username
		douyinOrder.BaseModel.UpdatedBy = admin.Username

		// 检查订单是否存在
		existingOrder, err := models.GetDouyinGroupOrderByOrderId(douyinOrder.OrderId)
		if err != nil {
			logs.Error("查询抖音订单失败: %v", err)
			continue
		}

		if existingOrder == nil {
			// 添加新订单
			douyinOrder.BaseModel.CreatedAt = time.Now().Unix()
			douyinOrder.BaseModel.UpdatedAt = douyinOrder.CreatedAt
			_, err = models.AddDouyinGroupOrder(douyinOrder)
			if err != nil {
				logs.Error("添加抖音订单失败: %v", err)
			}
		} else {
			// 更新现有订单
			douyinOrder.BaseModel.Id = existingOrder.Id
			douyinOrder.BaseModel.UpdatedAt = time.Now().Unix()
			err = models.UpdateDouyinGroupOrder(douyinOrder)
			if err != nil {
				logs.Error("更新抖音订单失败: %v", err)
			}
		}
	}

	// 更新最后同步时间
	douyin.LastSyncTime = time.Now().Unix()
	err = models.UpdateDouyin(douyin)
	if err != nil {
		logs.Error("更新抖音配置最后同步时间失败: %v", err)
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
	}
	c.ServeJSON()
}

// DouyinGroupController 抖音团购活动控制器
type DouyinGroupController struct {
	BaseController
}

// @router /api/v1/douyin/group [get]
func (c *DouyinGroupController) List() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Fail("未授权访问")
		return
	}

	// 获取分页参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("pageSize", 10)

	// 获取过滤条件
	filters := make(map[string]interface{})
	if storeId, err := c.GetInt64("store_id"); err == nil && storeId > 0 {
		filters["store_id"] = storeId
	}
	if status, err := c.GetInt("status"); err == nil && status != -1 {
		filters["status"] = status
	}
	if douyinId, err := c.GetInt64("douyin_id"); err == nil && douyinId > 0 {
		filters["douyin_id"] = douyinId
	}
	if title := c.GetString("title"); title != "" {
		filters["title"] = title
	}

	// 加盟商只能查看自己的数据
	if admin.FranchiseId > 0 {
		filters["franchise_id"] = admin.FranchiseId
	}

	// 查询数据
	list, total, err := models.GetDouyinGroupList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "获取抖音团购活动列表失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
		"data": map[string]interface{}{
			"list":  list,
			"total": total,
		},
	}
	c.ServeJSON()
}

// @router /api/v1/douyin/group [post]
func (c *DouyinGroupController) Create() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Fail("未授权访问")
		return
	}

	var group models.DouyinGroup
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &group); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "参数解析失败",
		}
		c.ServeJSON()
		return
	}

	// 验证抖音配置是否属于当前加盟商
	if group.DouyinId > 0 {
		douyin, err := models.GetDouyinById(group.DouyinId)
		if err != nil || douyin == nil {
			c.Data["json"] = map[string]interface{}{
				"code": 400,
				"msg":  "抖音配置不存在",
			}
			c.ServeJSON()
			return
		}

		if admin.FranchiseId > 0 && douyin.BaseModel.FranchiseId != admin.FranchiseId {
			c.Data["json"] = map[string]interface{}{
				"code": 403,
				"msg":  "没有权限使用此抖音配置",
			}
			c.ServeJSON()
			return
		}
	}

	// 设置创建者信息
	group.BaseModel.CreatedAt = time.Now().Unix()
	group.BaseModel.UpdatedAt = group.CreatedAt
	group.BaseModel.CreatedBy = admin.Username
	group.BaseModel.UpdatedBy = admin.Username

	// 设置加盟商ID
	group.BaseModel.FranchiseId = admin.FranchiseId

	// 添加数据
	id, err := models.AddDouyinGroup(&group)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "添加抖音团购活动失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
		"data": map[string]interface{}{
			"id": id,
		},
	}
	c.ServeJSON()
}

// @router /api/v1/douyin/group/:id [get]
func (c *DouyinGroupController) Detail() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Fail("未授权访问")
		return
	}

	id, err := c.GetInt64(":id")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "参数错误",
		}
		c.ServeJSON()
		return
	}

	// 查询数据
	group, err := models.GetDouyinGroupById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "获取抖音团购活动详情失败",
		}
		c.ServeJSON()
		return
	}
	if group == nil {
		c.Data["json"] = map[string]interface{}{
			"code": 404,
			"msg":  "抖音团购活动不存在",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if admin.FranchiseId > 0 && group.BaseModel.FranchiseId != admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"code": 403,
			"msg":  "没有权限访问此数据",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
		"data": group,
	}
	c.ServeJSON()
}

// @router /api/v1/douyin/group/:id [put]
func (c *DouyinGroupController) Update() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Fail("未授权访问")
		return
	}

	id, err := c.GetInt64(":id")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "参数错误",
		}
		c.ServeJSON()
		return
	}

	// 查询数据
	group, err := models.GetDouyinGroupById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "获取抖音团购活动详情失败",
		}
		c.ServeJSON()
		return
	}
	if group == nil {
		c.Data["json"] = map[string]interface{}{
			"code": 404,
			"msg":  "抖音团购活动不存在",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if admin.FranchiseId > 0 && group.BaseModel.FranchiseId != admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"code": 403,
			"msg":  "没有权限修改此数据",
		}
		c.ServeJSON()
		return
	}

	// 解析JSON数据
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, group); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "参数解析失败",
		}
		c.ServeJSON()
		return
	}

	// 设置更新者信息
	group.BaseModel.UpdatedAt = time.Now().Unix()
	group.BaseModel.UpdatedBy = admin.Username

	// 确保不改变所属加盟商
	group.BaseModel.FranchiseId = admin.FranchiseId

	// 更新数据
	err = models.UpdateDouyinGroup(group)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "更新抖音团购活动失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
	}
	c.ServeJSON()
}

// @router /api/v1/douyin/group/:id [delete]
func (c *DouyinGroupController) Delete() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Fail("未授权访问")
		return
	}

	id, err := c.GetInt64(":id")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "参数错误",
		}
		c.ServeJSON()
		return
	}

	// 查询数据，确保存在且属于当前加盟商
	group, err := models.GetDouyinGroupById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "获取抖音团购活动详情失败",
		}
		c.ServeJSON()
		return
	}
	if group == nil {
		c.Data["json"] = map[string]interface{}{
			"code": 404,
			"msg":  "抖音团购活动不存在",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if admin.FranchiseId > 0 && group.BaseModel.FranchiseId != admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"code": 403,
			"msg":  "没有权限删除此数据",
		}
		c.ServeJSON()
		return
	}

	// 删除数据
	err = models.DeleteDouyinGroup(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "删除抖音团购活动失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
	}
	c.ServeJSON()
}

// DouyinGroupOrderController 抖音团购订单控制器
type DouyinGroupOrderController struct {
	BaseController
}

// @router /api/v1/douyin/group/order [get]
func (c *DouyinGroupOrderController) List() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Fail("未授权访问")
		return
	}

	// 获取分页参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("pageSize", 10)

	// 获取过滤条件
	filters := make(map[string]interface{})
	if storeId, err := c.GetInt64("store_id"); err == nil && storeId > 0 {
		filters["store_id"] = storeId
	}
	if douyinId, err := c.GetInt64("douyin_id"); err == nil && douyinId > 0 {
		filters["douyin_id"] = douyinId
	}
	if douyinGroupId, err := c.GetInt64("douyin_group_id"); err == nil && douyinGroupId > 0 {
		filters["douyin_group_id"] = douyinGroupId
	}
	if status := c.GetString("status"); status != "" {
		filters["status"] = status
	}
	if processStatus := c.GetString("process_status"); processStatus != "" {
		filters["process_status"] = processStatus
	}
	if isProcessed, err := c.GetInt("is_processed"); err == nil && isProcessed != -1 {
		filters["is_processed"] = isProcessed
	}
	if isUsed, err := c.GetInt("is_used"); err == nil && isUsed != -1 {
		filters["is_used"] = isUsed
	}
	if startTime, err := c.GetInt64("start_time"); err == nil && startTime > 0 {
		filters["start_time"] = startTime
	}
	if endTime, err := c.GetInt64("end_time"); err == nil && endTime > 0 {
		filters["end_time"] = endTime
	}

	// 加盟商只能查看自己的数据
	if admin.FranchiseId > 0 {
		filters["franchise_id"] = admin.FranchiseId
	}

	// 查询数据
	list, total, err := models.GetDouyinGroupOrderList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "获取抖音团购订单列表失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
		"data": map[string]interface{}{
			"list":  list,
			"total": total,
		},
	}
	c.ServeJSON()
}

// @router /api/v1/douyin/group/order/:id [get]
func (c *DouyinGroupOrderController) Detail() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Fail("未授权访问")
		return
	}

	id, err := c.GetInt64(":id")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "参数错误",
		}
		c.ServeJSON()
		return
	}

	// 查询数据
	order, err := models.GetDouyinGroupOrderById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "获取抖音团购订单详情失败",
		}
		c.ServeJSON()
		return
	}
	if order == nil {
		c.Data["json"] = map[string]interface{}{
			"code": 404,
			"msg":  "抖音团购订单不存在",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if admin.FranchiseId > 0 && order.BaseModel.FranchiseId != admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"code": 403,
			"msg":  "没有权限访问此数据",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
		"data": order,
	}
	c.ServeJSON()
}

// @router /api/v1/douyin/group/order/:id/process [post]
func (c *DouyinGroupOrderController) Process() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Fail("未授权访问")
		return
	}

	id, err := c.GetInt64(":id")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "参数错误",
		}
		c.ServeJSON()
		return
	}

	// 查询数据，确保存在且属于当前加盟商
	order, err := models.GetDouyinGroupOrderById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "获取抖音团购订单详情失败",
		}
		c.ServeJSON()
		return
	}
	if order == nil {
		c.Data["json"] = map[string]interface{}{
			"code": 404,
			"msg":  "抖音团购订单不存在",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if admin.FranchiseId > 0 && order.BaseModel.FranchiseId != admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"code": 403,
			"msg":  "没有权限处理此订单",
		}
		c.ServeJSON()
		return
	}

	// 获取处理状态
	status, err := c.GetInt("status")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "参数错误",
		}
		c.ServeJSON()
		return
	}

	// 处理订单
	err = models.ProcessDouyinGroupOrder(id, status)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "处理抖音团购订单失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
	}
	c.ServeJSON()
}

// @router /api/v1/douyin/group/order/:id/use [post]
func (c *DouyinGroupOrderController) Use() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Fail("未授权访问")
		return
	}

	id, err := c.GetInt64(":id")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "参数错误",
		}
		c.ServeJSON()
		return
	}

	// 查询数据，确保存在且属于当前加盟商
	order, err := models.GetDouyinGroupOrderById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "获取抖音团购订单详情失败",
		}
		c.ServeJSON()
		return
	}
	if order == nil {
		c.Data["json"] = map[string]interface{}{
			"code": 404,
			"msg":  "抖音团购订单不存在",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if admin.FranchiseId > 0 && order.BaseModel.FranchiseId != admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"code": 403,
			"msg":  "没有权限使用此订单",
		}
		c.ServeJSON()
		return
	}

	// 检查订单是否已使用
	if order.IsUsed == 1 {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "该团购券已使用，不能重复使用",
		}
		c.ServeJSON()
		return
	}

	// 检查订单状态
	if order.Status != "CONFIRMED" && order.Status != "COMPLETED" {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "该团购订单尚未确认，不能使用",
		}
		c.ServeJSON()
		return
	}

	// 调用抖音API同步使用结果
	douyinService := services.NewDouyinAPIService()
	err = douyinService.UseVoucher(order.OrderId, order.VoucherCode)
	if err != nil {
		logs.Error("调用抖音API使用券码失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "调用抖音API失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 使用团购券
	err = models.UseDouyinGroupOrder(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "使用抖音团购券失败",
		}
		c.ServeJSON()
		return
	}

	// 创建验券记录
	verify := &models.GroupBuyVerify{
		GroupBuyActivityId: 0, // 抖音券没有对应的活动ID
		GroupBuyOrderId:    order.Id,
		MemberId:           0,
		StoreId:            order.StoreId,
		OperatorId:         admin.Id,
		OrderAmount:        float64(order.TotalPrice),
		VerifyTime:         time.Now().Unix(),
		Remark:             fmt.Sprintf("抖音团购券核销[订单号:%s]", order.OrderId),
	}

	_, err = models.CreateGroupBuyVerify(verify)
	if err != nil {
		logs.Error("创建抖音验券记录失败: %v", err)
		// 这里不返回错误，因为券已经使用成功
	}

	// 记录操作日志
	logs.Info("抖音团购券使用成功 - 订单ID: %d, 操作人: %d", id, admin.Id)

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
	}
	c.ServeJSON()
}

// @router /api/v1/douyin/group/order/sync [post]
func (c *DouyinGroupOrderController) Sync() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Fail("未授权访问")
		return
	}

	// 获取门店ID
	storeId, err := c.GetInt64("store_id")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "参数错误",
		}
		c.ServeJSON()
		return
	}

	// 获取抖音配置
	douyin, err := models.GetDouyinByStoreId(storeId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "获取抖音配置失败",
		}
		c.ServeJSON()
		return
	}
	if douyin == nil {
		c.Data["json"] = map[string]interface{}{
			"code": 404,
			"msg":  "抖音配置不存在",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if admin.FranchiseId > 0 && douyin.BaseModel.FranchiseId != admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"code": 403,
			"msg":  "没有权限操作此门店的抖音配置",
		}
		c.ServeJSON()
		return
	}

	// 创建抖音API服务
	apiService := services.NewDouyinAPIService()

	// 同步团购活动
	groups, err := apiService.SyncGroups(douyin.PoiId)
	if err != nil {
		logs.Error("同步抖音团购活动失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "同步抖音团购活动失败",
		}
		c.ServeJSON()
		return
	}

	// 更新团购活动
	for _, group := range groups {
		// 转换数据
		douyinGroup := &models.DouyinGroup{
			DouyinId:      douyin.Id,
			StoreId:       douyin.StoreId,
			StoreName:     douyin.StoreName,
			Title:         group["title"].(string),
			Description:   group["description"].(string),
			OriginalPrice: int(group["original_price"].(float64)),
			GroupPrice:    int(group["group_price"].(float64)),
			MinCount:      int(group["min_count"].(float64)),
			MaxCount:      int(group["max_count"].(float64)),
			StartTime:     int64(group["start_time"].(float64)),
			EndTime:       int64(group["end_time"].(float64)),
			Status:        int(group["status"].(float64)),
			DouyinGroupId: group["group_id"].(string),
			SoldCount:     int(group["sold_count"].(float64)),
			ActivityRules: group["activity_rules"].(string),
			ServiceTerms:  group["service_terms"].(string),
			Images:        group["images"].(string),
			LastSyncTime:  time.Now().Unix(),
		}

		// 设置加盟商ID和创建者信息
		douyinGroup.BaseModel.FranchiseId = douyin.FranchiseId
		douyinGroup.BaseModel.CreatedBy = admin.Username
		douyinGroup.BaseModel.UpdatedBy = admin.Username

		// 检查团购活动是否存在
		existingGroup, err := models.GetDouyinGroupByDouyinGroupId(douyinGroup.DouyinGroupId)
		if err != nil {
			logs.Error("查询抖音团购活动失败: %v", err)
			continue
		}

		if existingGroup == nil {
			// 添加新团购活动
			douyinGroup.BaseModel.CreatedAt = time.Now().Unix()
			douyinGroup.BaseModel.UpdatedAt = douyinGroup.CreatedAt
			_, err = models.AddDouyinGroup(douyinGroup)
			if err != nil {
				logs.Error("添加抖音团购活动失败: %v", err)
			}
		} else {
			// 更新现有团购活动
			douyinGroup.BaseModel.Id = existingGroup.Id
			douyinGroup.BaseModel.UpdatedAt = time.Now().Unix()
			err = models.UpdateDouyinGroup(douyinGroup)
			if err != nil {
				logs.Error("更新抖音团购活动失败: %v", err)
			}
		}
	}

	// 同步订单
	// 获取最近24小时的订单
	startTime := time.Now().Add(-24 * time.Hour).Unix()
	endTime := time.Now().Unix()
	orders, err := apiService.SyncOrders(douyin.PoiId, startTime, endTime)
	if err != nil {
		logs.Error("同步抖音订单失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "同步抖音订单失败",
		}
		c.ServeJSON()
		return
	}

	// 更新订单
	for _, order := range orders {
		// 转换数据
		douyinOrder := &models.DouyinGroupOrder{
			DouyinId:         douyin.Id,
			StoreId:          douyin.StoreId,
			StoreName:        douyin.StoreName,
			OrderId:          order["order_id"].(string),
			OrderTime:        int64(order["order_time"].(float64)),
			GroupTitle:       order["group_title"].(string),
			UserName:         order["user_name"].(string),
			UserPhone:        order["user_phone"].(string),
			Quantity:         int(order["quantity"].(float64)),
			TotalPrice:       int(order["total_price"].(float64)),
			Status:           order["status"].(string),
			ProcessStatus:    order["process_status"].(string),
			IsProcessed:      int(order["is_processed"].(float64)),
			ProcessTime:      int64(order["process_time"].(float64)),
			RefundStatus:     order["refund_status"].(string),
			Remark:           order["remark"].(string),
			DouyinRemark:     order["douyin_remark"].(string),
			VoucherCode:      order["voucher_code"].(string),
			VoucherValidTime: int64(order["voucher_valid_time"].(float64)),
			IsUsed:           int(order["is_used"].(float64)),
			UseTime:          int64(order["use_time"].(float64)),
		}

		// 设置加盟商ID和创建者信息
		douyinOrder.BaseModel.FranchiseId = douyin.FranchiseId
		douyinOrder.BaseModel.CreatedBy = admin.Username
		douyinOrder.BaseModel.UpdatedBy = admin.Username

		// 检查订单是否存在
		existingOrder, err := models.GetDouyinGroupOrderByOrderId(douyinOrder.OrderId)
		if err != nil {
			logs.Error("查询抖音订单失败: %v", err)
			continue
		}

		if existingOrder == nil {
			// 添加新订单
			douyinOrder.BaseModel.CreatedAt = time.Now().Unix()
			douyinOrder.BaseModel.UpdatedAt = douyinOrder.CreatedAt
			_, err = models.AddDouyinGroupOrder(douyinOrder)
			if err != nil {
				logs.Error("添加抖音订单失败: %v", err)
			}
		} else {
			// 更新现有订单
			douyinOrder.BaseModel.Id = existingOrder.Id
			douyinOrder.BaseModel.UpdatedAt = time.Now().Unix()
			err = models.UpdateDouyinGroupOrder(douyinOrder)
			if err != nil {
				logs.Error("更新抖音订单失败: %v", err)
			}
		}
	}

	// 更新最后同步时间
	douyin.LastSyncTime = time.Now().Unix()
	err = models.UpdateDouyin(douyin)
	if err != nil {
		logs.Error("更新抖音配置最后同步时间失败: %v", err)
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
	}
	c.ServeJSON()
}
